package cn.cjlmonster.hyouka_assistant.ai

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.FrameLayout
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import cn.cjlmonster.hyouka_assistant.WKPlugin
import cn.cjlmonster.hyouka_assistant.audio.AudioRecorder
import cn.cjlmonster.hyouka_assistant.base.BaseActivity
import cn.cjlmonster.hyouka_assistant.databinding.ActivityAiAssistantBinding
import cn.cjlmonster.hyouka_assistant.utils.DPKits
import cn.cjlmonster.hyouka_assistant.webView.CustomWebChromeClient
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


/**
 * 智能语音助手
 *
 * @author cjl
 * @date 2025/6/22 14:49
 */
class AIAssistantActivity : BaseActivity<ActivityAiAssistantBinding>() {

    companion object {
        const val TAG = WKPlugin.TAG
    }

    override fun createBinding() = ActivityAiAssistantBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        AudioRecorder.createRecord()
    }

    override fun bindWebView() = binding.webView

    override fun initViewModel() {
        immersiveNavigationBar()
        binding.bg.post {
            val params = binding.bg.layoutParams as FrameLayout.LayoutParams
            val marginTop = intent.getIntExtra("marginTop", 57)
            params.topMargin = DPKits.dp2px(this, marginTop.toFloat())
            binding.bg.layoutParams = params
            val height = binding.bg.measuredHeight
            binding.bg.translationY = height.toFloat()
            AnimatorSet().run {
                playTogether(
                    ObjectAnimator.ofFloat(binding.bg, "translationY", height.toFloat(), 0f),
                )
                duration = 300
                interpolator = DecelerateInterpolator()
                start()
            }
        }
        binding.webView.setWebViewClient(object : WebViewClient() {

            var isLoadFinish = false
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                binding.webView.alpha = 0f
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                if (isLoadFinish) return
                isLoadFinish = true
                lifecycleScope.launch {
                    delay(300)
                    binding.progressBar.isVisible = false
                    ObjectAnimator.ofFloat(binding.webView, "alpha", 0f, 1f).run {
                        duration = 150
                        interpolator = DecelerateInterpolator()
                        start()
                    }
                }
            }
        })
        binding.webView.setWebChromeClient(object : CustomWebChromeClient(this) {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                binding.progressBar.progress = newProgress
            }
        })
        AIAssistantBridge(this, binding.webView) {
            val bgHeight = binding.bg.measuredHeight.toFloat()
            val webViewHeight = binding.webView.measuredHeight.toFloat()
            AnimatorSet().run {
                playTogether(
                    ObjectAnimator.ofFloat(binding.bg, "translationY", 0f, bgHeight),
                    ObjectAnimator.ofFloat(binding.bg, "alpha", 1f, 0f),
                    ObjectAnimator.ofFloat(binding.webView, "translationY", 0f, webViewHeight),
                    ObjectAnimator.ofFloat(binding.webView, "alpha", 1f, 0f)
                )
                duration = 150
                interpolator = AccelerateInterpolator()
                addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator) {
                        finish()
                    }
                })
                start()
            }
        }
    }

    override fun initData() {
        val url = intent.getStringExtra("url") ?: ""
        Log.i(TAG, "智能语音助手: $url")
        binding.webView.postDelayed({ binding.webView.loadUrl(url) }, 100)
    }

    override fun onDestroy() {
        super.onDestroy()
        AudioRecorder.destroyRecord()
        try {
            binding.webView.destroy()
        } catch (e: Exception) {
            Log.e(TAG, "onDestroy: ", e)
        }
    }

}